const express = require('express')
const Router = express.Router()
const query = require('./db')
const { randomNum, messageAlivePushing } = require('../utils/tool')


module.exports = Router

/**
 * 当前用户的关注和粉丝列表
 */
Router.get('/followList', async (req, res) => {
    try {
        let { user_id } = req.query
        let followListResult = await query(`select * from follow where fans_id='${user_id}'`)
        let fansListResult = await query(`select * from follow where follow_id='${user_id}'`)

        let followUserList = []//关注列表
        let fansUserList = []//粉丝列表

        async function processItems(list, type) {
            for (const item of list) {
                let result = await query(`select * from user where user_id='${type === 'follow' ? item.follow_id : item.fans_id}'`)
                if (type === 'follow') {
                    followUserList.push(result[0])
                    // followUserList = result
                } else if (type === 'fans') {
                    fansUserList.push(result[0])
                    // fansUserList = result
                }
            }
        }

        await processItems(followListResult, 'follow')
        await processItems(fansListResult, 'fans')

        res.send({
            code: 200,
            msg: '获取关注粉丝列表成功',
            data: {
                followUserList,
                fansUserList,
            }
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 关注/取消
 */
Router.post('/changeFollow', async (req, res) => {
    try {
        // user_id:本人；follow_id：要关注的人
        let { user_id, follow_id, follow_flag } = req.body
        let changeFollowResult
        let messageResult = ""  // 信息表增加的推送信息数据
        // 判断当前是否已经关注
        if (follow_flag) {  //没关注
            changeFollowResult = await query(`insert into follow values(${null},'${follow_id}','${user_id}')`)
            // 生成推送信息
            messageResult = await query(`insert into message values(${null},'新增一位粉丝','','guanzhu','${Date.now()}',${follow_id},${user_id},${null},'0')`)

        } else {    //已关注
            changeFollowResult = await query(`delete from follow where follow_id='${follow_id}' and fans_id='${user_id}'`)
            // 生成推送信息
            messageResult = await query(`insert into message values(${null},'失去一位粉丝','','guanzhu','${Date.now()}',${follow_id},${user_id},${null},'0')`)
        }

        let messagePushingData = await query(`select * from message inner join user on message.message_from_user_id=user.user_id where message_to_user_id=${follow_id} and message_from_user_id<>message_to_user_id group by message_id`)
        // 推送消息
        messageAlivePushing(String(follow_id), messagePushingData)

        res.send({
            code: 200,
            msg: '关注/取消成功',
            changeFollowResult,
            flag: !follow_flag
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 判断当前访问的用户是否已经关注
 */
Router.get('/judgeFollow', async (req, res) => {
    try {
        let { user_id, visit_id } = req.query
        if (user_id === visit_id) {
            res.send({
                code: 401,
                msg: "当前作者是自己"
            })
            return
        }
        let data = await query(`select * from follow where follow_id='${visit_id}' and fans_id='${user_id}'`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: "当前作者没有关注"
            })
            return
        }
        res.send({
            code: 200,
            msg: "当前作者已经关注",
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})